package com.alibaba.sdk.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.enums.ErrorCodeEnums;
import com.alibaba.sdk.exception.BusinessException;
import com.alibaba.sdk.model.BaseResponse;
import com.alibaba.sdk.model.OperationResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 返回值校验
 *
 * @ writer Shawn(Shawn_0217@163.com)
 * @ date & time 2021/4/26 21:05
 * @ company alibaba
 */
@Component
@Aspect
@Order(1)
@Slf4j
public class ValidResponseAspect {

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.alibaba.sdk.annotation.ValidResponse)")
    public void pointCut() {}

    /**
     * 方法执行完,返回值后置校验
     *
     * @param response
     */
    @AfterReturning(returning = "response", pointcut = "pointCut()")
    public void afterAdvice(BaseResponse<Object> response) {
        if (response != null) {
            log.info("接口返回数据: {}", JSONObject.toJSONString(response));
            String message = response.getErrorMsg();
            if (!OperationResult.OK.equals(message)) {
                throw new BusinessException(response.getErrorCode(), response.getErrorMsg());
            }
        } else {
            throw new BusinessException(ErrorCodeEnums.DATA_EMPTY);
        }
    }
}
